#include "motor.h"

int PWM_MAX = 7200, PWM_MIN = -7200;
int motor1, motor2; 

/**
 * @brief 电机PWM初始化（10kHZ）
 * @param None
 * @retval None
 **/
void MotorPWM_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	TIM_OCInitTypeDef TIM_OCInitStruct;
	//使能时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
	//使能GPIO
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;	
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_8|GPIO_Pin_11;
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStruct);
	//定时器基本配置
	TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct);
	TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;	
	TIM_TimeBaseInitStruct.TIM_Period=7199;		
	TIM_TimeBaseInitStruct.TIM_Prescaler=0;			
	TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM1,&TIM_TimeBaseInitStruct);	
	//输出比较结构体初始化
	TIM_OCInitStruct.TIM_OCMode=TIM_OCMode_PWM1;
	TIM_OCInitStruct.TIM_OCPolarity=TIM_OCPolarity_High;
	TIM_OCInitStruct.TIM_OutputState=TIM_OutputState_Enable;
	TIM_OCInitStruct.TIM_Pulse=0;
	TIM_OC1Init(TIM1,&TIM_OCInitStruct);	
	TIM_OC4Init(TIM1,&TIM_OCInitStruct);
	
	//高级定时器专属--MOE主输出使能
	TIM_CtrlPWMOutputs(TIM1,ENABLE);	

	TIM_OC1PreloadConfig(TIM1,TIM_OCPreload_Enable);
	TIM_OC4PreloadConfig(TIM1,TIM_OCPreload_Enable);
	TIM_ARRPreloadConfig(TIM1,ENABLE);	
	//开启定时器
	TIM_Cmd(TIM1,ENABLE);
}


/**
 * @brief 电机初始化
 * @note PB3 PB4作为普通IO口使用要关闭JTAG
 * @param  无
 * @retval  无
 **/
void Motor_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_3 | GPIO_Pin_4;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStruct);
	
	MotorPWM_Init();
}


/**
 * @brief 电机限幅
 * @param  限幅电机地址值
 * @retval  无
 **/
void Limit(int *motorA, int *motorB)
{
	if (*motorA > PWM_MAX)
	{
		*motorA = PWM_MAX;
	}
	if (*motorA < PWM_MIN)
	{
		*motorA = PWM_MIN;
	}

	if (*motorB > PWM_MAX)
	{
		*motorB = PWM_MAX;
	}
	if (*motorB < PWM_MIN)
	{
		*motorB = PWM_MIN;
	}
}
/**
 * @brief 绝对值函数
 * @param  值
 * @retval  绝对值
 **/
int MyAbs(int p)
{
	return (p >= 0 ? p : (-p));
}

/**
 * @brief 载入电机
 * @param 左右轮pwm
 * @retval 无
 **/
void load(int motor1, int motor2)
{
	if (motor1 > 0)
	{
		Ain1 = 1;
		Ain2 = 0;
	}
	else
	{
		Ain1 = 0;
		Ain2 = 1;
	}
	TIM_SetCompare1(TIM1, MyAbs(motor1)); 
	
	if (motor2 > 0)
	{
		Bin1 = 1;
		Bin2 = 0;
	}
	else
	{
		Bin1 = 0;
		Bin2 = 1;
	}
	TIM_SetCompare4(TIM1, MyAbs(motor2));
}

/**
 * @brief 停车
 * @param None
 * @retval None
 **/
void brake(void)
{
	Ain1 = 1;
	Ain2 = 1;
	Bin1 = 1;
	Bin2 = 1;
}